package enumdemo;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public enum TestEnum {
    //枚举对象
    RED("red",1), BLACK("black",2), GREEN("green",3), WHITE("white",4);
    private String name;
    private int key;

    private TestEnum(String name, int key) {
        this.name = name;
        this.key = key;
    }
    public static TestEnum getEnumKey(int key) {
        for(TestEnum t : TestEnum.values()) {
            if(t.key == key) {
                return t;
            }
        }
        return null;
    }

    public static void reflectPrivateConstructor() {
        try {
            //forName根据全路径找到class类 注意我这里TestEnum是在enumdemo的包里的
            Class<?> classStudent = Class.forName("enumdemo.TestEnum");

            //调用getDeclaredConstructor方法来获得对应的构造方法，当前枚举的构造方法中有两个参数String和int
            Constructor<?> declareConstructorStudent = classStudent.getDeclaredConstructor(String.class, int.class,String.class,int.class);

            //设置去为true后有了可修改访问的权限
            declareConstructorStudent.setAccessible(true);

            //调用获得的构造方法来实例化一个枚举
            Object objectStudent = declareConstructorStudent.newInstance("黄色",999);

            TestEnum testEnum = (TestEnum) objectStudent;

            System.out.println("获得枚举的私有构造函数" + testEnum);
        } catch (ClassNotFoundException | NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        reflectPrivateConstructor();
    }
    public static void main3(String[] args) {
        System.out.println(getEnumKey(2));
    }

    public static void main2(String[] args) {

        //拿到枚举实例 BLACK
        TestEnum testEnum = TestEnum.BLACK;

        //拿到枚举实例 RED
        TestEnum testEnum1 = TestEnum.RED;

        //compareTo方法是比较两个枚举实例定义时候的顺序的
        System.out.println(testEnum.compareTo(testEnum1));
        System.out.println(BLACK.compareTo(RED));
        System.out.println(RED.compareTo(BLACK));
    }
    public static void main1(String[] args) {

        //枚举的values方法 和 ordinal方法
        TestEnum[] testEnum = TestEnum.values();
        for (int i = 0; i < testEnum.length; i++) {

            System.out.print(testEnum[i] + " " + testEnum[i].ordinal());
        }
        System.out.println();
        //枚举的valueOf方法
        System.out.println(TestEnum.valueOf("GREEN"));
    }
}
